<template>
  <TresDirectionalLight :position="[-0.5, 5, 1.5]" :intensity="1.5" />
  <TresAmbientLight :intensity="0.8" />
  <primitive v-if="scene" :object="scene" />
</template>

<script setup lang="ts">
import * as THREE from "three";
import { TextureLoader } from "three";
import { useGraph, useLoader } from "@tresjs/core";
import { useAnimations } from "@tresjs/cientos";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import { ref, watch } from "vue";

const emits = defineEmits(["animationEnd"]);
const { state: model } = await useLoader(GLTFLoader, "./model/fly2.glb");
const { state: texture } = await useLoader(TextureLoader, "./ui/content3.png");
const isRotationEnd = ref(false); // 旋转结束标志
const st = ref<any>(null);
const animationId = ref<any>(null);

// 关键设置：优化清晰度
texture.value.anisotropy = 1;
texture.value.colorSpace = THREE.SRGBColorSpace;
texture.value.generateMipmaps = false; // 确保生成Mipmap（通常默认true）
texture.value.magFilter = THREE.NearestFilter; // 关键设置：放大时使用最近邻过滤，保持锐利
texture.value.minFilter = THREE.LinearFilter;

const props = defineProps({
  isFlying: {
    type: Boolean,
    default: false,
  },
  craneColor: {
    type: String,
    default: "#fdde05",
  },
});
const graph = useGraph(model.value?.scene as any);
// console.log("graph:", graph.value);
// 提取模型
const scene = graph.value?.nodes.Center;

// 隐藏zhishe_mesh
if (graph.value?.nodes.zhihe_mesh) {
  graph.value.nodes.Scene.children[0].visible = false;
}
if (scene?.children[0]) {
  scene.children[0].visible = false;
}

// 设置材质
if (scene?.children[1]) {
  scene?.children[1].children.forEach((child: any) => {
    if (child.isMesh) {
      child.material = new THREE.MeshBasicMaterial({
        name: "02 - Default",
        color: new THREE.Color("#e7ba81"), // 光泽颜色
        map: texture.value,
        side: 2,
      });
    }
  });
}
// 设置位置和旋转
scene?.position.set(0, 6, -0.5);
scene?.rotation.set(
  Math.PI * (-75 / 180),
  Math.PI * (-50 / 180), // 竖轴
  Math.PI * (-20 / 180) // 横轴
);

// 播放动画
const { actions } = useAnimations(
  model.value.animations,
  graph.value?.nodes.Scene as any
);
Object.keys(actions).forEach((key) => {
  const animation = actions[key];
  animation?.play();
});

// 更改材质颜色
const changeColor = (color: string) => {
  if (scene?.children[1]) {
    scene.children[1].children.forEach((child: any) => {
      if (child.isMesh) {
        child.material = new THREE.MeshStandardMaterial({
          name: "02 - Default",
          blending: 1,
          color: new THREE.Color(color),
          //emissive: new THREE.Color("#e7ba81"),
          lightMapIntensity: 1,
          side: 2,
        });
      }
    });
  }
};

const setRotationEnd = (value: boolean) => {
  if (st.value) {
    return;
  }
  st.value = setTimeout(() => {
    isRotationEnd.value = value; // 延迟设置，确保动画完成后再设置
  }, 200);
};
// 在动画循环中更新TWEEN
function animate() {
  animationId.value = requestAnimationFrame(animate);
  if (scene?.rotation.y < Math.PI * (120 / 180)) {
    const rotationSpeed = 0.4; // 调整旋转速度
    const newY = rotationSpeed * Math.PI * (10 / 180) + scene?.rotation.y; // 绕Y轴旋转
    scene?.rotation.set(Math.PI * (-45 / 180), newY, Math.PI * (0 / 180));
  } else {
    setRotationEnd(true); // 标记旋转结束
  }
  if (isRotationEnd.value) {
    const speedPosY = 0.3; // 调整旋转速度
    const speedPosZ = speedPosY * 0.305; // 调整旋转速度
    scene?.position.setX(0.5);
    if (scene?.position.y >= -25) {
      const newPosY = scene?.position.y - speedPosY;
      scene?.position.setY(newPosY);
    }
    if (scene?.position.z >= -10) {
      const newPosZ = scene?.position.z - speedPosZ;
      scene?.position.setZ(newPosZ);
    }
    if (scene?.position.y < -25 && scene?.position.z < -10) {
      clearTimeout(st.value);
      st.value = null;
      if (animationId.value) {
        cancelAnimationFrame(animationId.value);
      }
      emits("animationEnd");
    }
  }
}

watch(
  () => props.isFlying, // 监听场景的变化
  () => {
    if (props.isFlying) {
      const finalRotation = (scene?.rotation.y % Math.PI) * 2; // 最终旋转角度
      scene?.rotation.set(
        Math.PI * (-75 / 180),
        finalRotation,
        Math.PI * (-20 / 180)
      );
      animate(); //
    }
  },
  { immediate: true, deep: true } // 立即执行一次，以确保初始颜色正确设置
);

watch(
  () => props.craneColor, // 监听场景的变化
  () => {
    changeColor(props.craneColor); // 调用函数来更改材质颜色，传递新的颜色作为参数
  },
  { immediate: false, deep: true } // 立即执行一次，以确保初始颜色正确设置
);

defineExpose({ changeColor, scene });
</script>
